//
//  JWTextPickerManager+Rx.swift
//  oa
//
//  Created by Linjw on 2022/3/15.
//

import UIKit

#if canImport(RxSwift)
import RxSwift
#endif
#if canImport(RxCocoa)
import RxCocoa
#endif


public enum JWTextPickerSelectedType {
    /// 通过index
    case index(first: Int, second: Int, third: Int)
    /// 通过id
    case ids(first: String?, second: String?, third: String?)
    /// 通过text
    case text(first: String?, second: String?, third: String?)
}

public extension Reactive where Base: JWTextPickerManager {
    
    /// 多文本选择器
    public static func showCombinePicker(list: [PickerTextProtocol],
                                    type: JWTextPickerColumnsType = .one,
                                    title: String = "",
                                    selectedType: JWTextPickerSelectedType?,
                                    styleConfig: JWTextPickerViewConfig = JWTextPickerViewConfig.defaultConfig(),
                                    presentedViewController: UIViewController? = nil)
    -> Observable<(firstModel: PickerTextProtocol, secondModel: PickerTextProtocol?, threeModel: PickerTextProtocol?)> {
        return Observable.create { (observer) -> Disposable in
            
            UIApplication.shared.keyWindow?.endEditing(true)
            
            let manager = JWTextPickerManager(title: title, type: type, dataSources: list)
            
            if let selectedType = selectedType {
                switch selectedType {
                case .ids(first: let firstId, second: let secondId, third: let thirdId):
                    var firstIndex = 0, secondIndex = 0, thirdIndex = 0
                    firstIndex = list.firstIndex { $0.pickerId == firstId  } ?? 0
                    if list.count > firstIndex {
                        let secondList = list[firstIndex].pickerItemList
                        secondIndex = secondList.firstIndex { $0.pickerId == secondId  } ?? 0
                        if secondList.count > secondIndex {
                            let thirdList = secondList[secondIndex].pickerItemList
                            thirdIndex = thirdList.firstIndex { $0.pickerId == thirdId  } ?? 0
                        }
                    }
                    manager.selectedIndexs.firstIndex = firstIndex
                    manager.selectedIndexs.secondIndex = secondIndex
                    manager.selectedIndexs.thirdIndex = thirdIndex
                case let .text(first: firstText, second: secondText, third: thirdText):
                    var firstIndex = 0, secondIndex = 0, thirdIndex = 0
                    firstIndex = list.firstIndex { $0.pickerText == firstText  } ?? 0
                    if list.count > firstIndex {
                        let secondList = list[firstIndex].pickerItemList
                        secondIndex = secondList.firstIndex { $0.pickerText == secondText  } ?? 0
                        if secondList.count > secondIndex {
                            let thirdList = secondList[secondIndex].pickerItemList
                            thirdIndex = thirdList.firstIndex { $0.pickerText == thirdText  } ?? 0
                        }
                    }
                    manager.selectedIndexs.firstIndex = firstIndex
                    manager.selectedIndexs.secondIndex = secondIndex
                    manager.selectedIndexs.thirdIndex = thirdIndex
                case .index(first: let firstIndex, second: let secondIndex, third: let thirdIndex):
                    manager.selectedIndexs.firstIndex = firstIndex
                    manager.selectedIndexs.secondIndex = secondIndex
                    manager.selectedIndexs.thirdIndex = thirdIndex
                }
            }
            
           
            let view = JWPickerViewController(combinationProtocol: manager, styleConfig: styleConfig)
                        
            manager.cancelCallBack = { info in
                observer.onCompleted()
            }
            //
            manager.confirmCallBack = { (contentView: JWPickerViewController, result: (firstModel: PickerTextProtocol, secondModel: PickerTextProtocol?, threeModel: PickerTextProtocol?)) in
                observer.onNext(result)
                observer.onCompleted()
            }
            
            let fromVc = presentedViewController != nil ? presentedViewController : JWTextPickerManager.topMost
            fromVc?.present(view, animated: true, completion: { })
            
            return Disposables.create {
                view.dismiss(animated: true, completion: nil)
            }
        }
    }
    
}

/// 文本选择器管理
extension JWTextPickerManager {
    
    /// 多文本选择器
    public static func rxShowCombinePicker(list: [PickerTextProtocol],
                                    type: JWTextPickerColumnsType = .one,
                                    title: String = "",
                                    selectedType: JWTextPickerSelectedType?,
                                    styleConfig: JWTextPickerViewConfig = JWTextPickerViewConfig.defaultConfig(),
                                    presentedViewController: UIViewController? = nil)
    -> Observable<(firstModel: PickerTextProtocol, secondModel: PickerTextProtocol?, threeModel: PickerTextProtocol?)> {
        return JWTextPickerManager.rx.showCombinePicker(list: list,
                                                        type: type,
                                                        title: title,
                                                        selectedType: selectedType,
                                                        styleConfig: styleConfig,
                                                        presentedViewController: presentedViewController)
    }
    
}

private extension JWTextPickerManager {
    
    /// 获取活动的VC
    static var topMost: UIViewController? {
        return self.topViewController(with: self.currentWindow()?.rootViewController)
    }

    /// 找到当前显示的UIWindow
    static func currentWindow() -> UIWindow? {
        
        var window: UIWindow? = UIApplication.shared.keyWindow
        if window?.windowLevel != UIWindow.Level.normal {
            for tempWindow in UIApplication.shared.windows.reversed() {
                if tempWindow.windowLevel == UIWindow.Level.normal {
                    window = tempWindow
                    break
                }
            }
        }
        return window
    }
    
    ///
    static func topViewController(with vc: UIViewController?) -> UIViewController? {
        
        guard let viewController = vc else { return nil }
        
        if let presented = viewController.presentedViewController {
            return self.topViewController(with: presented)
        } else if let tab = viewController as? UITabBarController {
            return self.topViewController(with: tab.selectedViewController)
        } else if let nav = viewController as? UINavigationController {
            return self.topViewController(with: nav.visibleViewController)
        } else {
            return viewController
        }
    }
    
}
